<template>
  <div class="room-detail">
    <div class="page-header">
      <div class="header-left">
        <el-page-header @back="goBack" :content="roomInfo.unit_number || '房间详情'"></el-page-header>
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/admin/assets/BuildingList' }">空间管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/admin/assets/BuildingDetail/${roomInfo.building ? roomInfo.building.building_id : ''}` }">{{ roomInfo.building ? roomInfo.building.name : '' }}</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/admin/assets/FloorDetail/${roomInfo.floor ? roomInfo.floor.floor_id : ''}` }">{{ roomInfo.floor ? roomInfo.floor.floor_number + '层' : '' }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ roomInfo.unit_number }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="openDialog">编辑信息</el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card v-loading="loading" class="info-card">
          <div class="card-header">
            <h3>房间基本信息</h3>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">房间ID：</span>
                <span class="value">{{ roomInfo.unit_id }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">房间号：</span>
                <span class="value">{{ roomInfo.unit_number }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">所属楼宇：</span>
                <span class="value">{{ roomInfo.building ? roomInfo.building.name : '-' }}</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">所属楼层：</span>
                <span class="value">{{ roomInfo.floor ? roomInfo.floor.floor_number + '层' : '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">实际面积：</span>
                <span class="value">{{ roomInfo.actual_area }} ㎡</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">建筑面积：</span>
                <span class="value">{{ roomInfo.building_area }} ㎡</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">房间类型：</span>
                <span class="value">{{ roomInfo.unit_type }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">当前状态：</span>
                <span class="value">
                  <el-tag :type="getRoomStatusType(roomInfo.status)">{{ roomInfo.status }}</el-tag>
                </span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">朝向：</span>
                <span class="value">{{ roomInfo.orientation || '-' }}</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">租金：</span>
                <span class="value">{{ roomInfo.rental_price }} 元/月</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">售价：</span>
                <span class="value">{{ roomInfo.sale_price }} 元</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">物业费标准：</span>
                <span class="value">{{ roomInfo.property_fee_standard }} 元/㎡/月</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="info-item">
                <span class="label">配套设施描述：</span>
                <span class="value">{{ roomInfo.facilities_desc || '无' }}</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ roomInfo.created_at }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ roomInfo.updated_at }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="contract-card" v-if="roomInfo.status === '已租' || roomInfo.status === '已售'">
          <div class="card-header">
            <h3>合同信息</h3>
            <el-button type="text" @click="viewContract">查看合同详情</el-button>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">合同编号：</span>
                <span class="value">{{ contractInfo?.contract_number }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">租户/业主：</span>
                <span class="value">{{ contractInfo?.tenant_name }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">联系电话：</span>
                <span class="value">{{ contractInfo?.tenant_phone }}</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">开始日期：</span>
                <span class="value">{{ contractInfo?.start_date }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">结束日期：</span>
                <span class="value">{{ contractInfo?.end_date }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">合同状态：</span>
                <span class="value">
                  <el-tag :type="getContractStatusType(contractInfo?.status)">{{ contractInfo?.status }}</el-tag>
                </span>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="room-image-card">
          <div class="card-header">
            <h3>房间图片</h3>
            <el-button type="text" icon="el-icon-edit" @click="uploadRoomImages">管理图片</el-button>
          </div>
          <div class="room-image-container">
            <div v-if="roomImages.length > 0" class="room-images">
              <el-carousel :interval="4000" type="card" height="200px">
                <el-carousel-item v-for="(image, index) in roomImages" :key="index">
                  <img :src="image.url" :alt="'房间图片' + (index + 1)" class="room-image" />
                </el-carousel-item>
              </el-carousel>
            </div>
            <div v-else class="room-image-placeholder">
              <i class="el-icon-picture-outline"></i>
              <p>暂无图片</p>
              <el-button size="small" type="primary" @click="uploadRoomImages">上传图片</el-button>
            </div>
          </div>
        </el-card>

        <el-card class="equipment-card">
          <div class="card-header">
            <h3>设备设施</h3>
            <el-button type="text" @click="manageEquipment">管理设备</el-button>
          </div>
          <div class="equipment-list">
            <el-table
              :data="equipmentList"
              border
              style="width: 100%">
              <el-table-column
                prop="device_name"
                label="设备名称">
              </el-table-column>
              <el-table-column
                prop="device_type"
                label="类型"
                width="100">
              </el-table-column>
              <el-table-column
                prop="status"
                label="状态"
                width="100">
                <template #default="scope">
                  <el-tag :type="getEquipStatusType(scope.row.status)">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 房间编辑对话框 -->
    <el-dialog title="编辑房间信息" v-model:visible="dialogVisible" width="650px">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">
        <el-form-item label="房间号" prop="unit_number">
          <el-input v-model="editForm.unit_number" placeholder="请输入房间号"></el-input>
        </el-form-item>
        <el-form-item label="实际面积" prop="actual_area">
          <el-input v-model="editForm.actual_area" placeholder="请输入实际面积">
            <template #append>㎡</template>
          </el-input>
        </el-form-item>
        <el-form-item label="建筑面积" prop="building_area">
          <el-input v-model="editForm.building_area" placeholder="请输入建筑面积">
            <template #append>㎡</template>
          </el-input>
        </el-form-item>
        <el-form-item label="房间类型" prop="unit_type">
          <el-select v-model="editForm.unit_type" placeholder="请选择类型">
            <el-option label="办公室" value="办公室"></el-option>
            <el-option label="商铺" value="商铺"></el-option>
            <el-option label="车位" value="车位"></el-option>
            <el-option label="仓库" value="仓库"></el-option>
            <el-option label="会议室" value="会议室"></el-option>
            <el-option label="广告位" value="广告位"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="空置" value="空置"></el-option>
            <el-option label="意向" value="意向"></el-option>
            <el-option label="已租" value="已租"></el-option>
            <el-option label="已售" value="已售"></el-option>
            <el-option label="装修中" value="装修中"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="待清洁" value="待清洁"></el-option>
            <el-option label="不可用" value="不可用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租金" prop="rental_price">
          <el-input v-model="editForm.rental_price" placeholder="请输入租金">
            <template #append>元/月</template>
          </el-input>
        </el-form-item>
        <el-form-item label="售价" prop="sale_price">
          <el-input v-model="editForm.sale_price" placeholder="请输入售价">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="物业费标准" prop="property_fee_standard">
          <el-input v-model="editForm.property_fee_standard" placeholder="请输入物业费标准">
            <template #append>元/㎡/月</template>
          </el-input>
        </el-form-item>
        <el-form-item label="朝向" prop="orientation">
          <el-select v-model="editForm.orientation" placeholder="请选择朝向">
            <el-option label="东" value="东"></el-option>
            <el-option label="南" value="南"></el-option>
            <el-option label="西" value="西"></el-option>
            <el-option label="北" value="北"></el-option>
            <el-option label="东南" value="东南"></el-option>
            <el-option label="东北" value="东北"></el-option>
            <el-option label="西南" value="西南"></el-option>
            <el-option label="西北" value="西北"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配套设施描述" prop="facilities_desc">
          <el-input type="textarea" v-model="editForm.facilities_desc" placeholder="请输入配套设施描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传图片对话框 -->
    <el-dialog title="管理房间图片" v-model:visible="uploadDialogVisible" width="650px">
      <el-upload
        class="upload-container"
        action="#"
        :auto-upload="false"
        :limit="5"
        multiple
        list-type="picture-card">
        <i class="el-icon-plus"></i>
        <template #tip>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUpload">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoomDetail, getRoomDevices, getRoomContract } from '@/api/assets.js'

export default {
  name: 'RoomDetail',
  data() {
    return {
      loading: false,
      roomId: '',
      roomInfo: {
        unit_id: '',
        building: {
          building_id: '',
          name: ''
        },
        floor: {
          floor_id: '',
          floor_number: ''
        },
        unit_number: '',
        actual_area: '',
        building_area: '',
        unit_type: '',
        status: '',
        rental_price: '',
        sale_price: '',
        property_fee_standard: '',
        orientation: '',
        facilities_desc: '',
        created_at: '',
        updated_at: ''
      },
      contractInfo: null,
      roomImages: [],
      equipmentList: [],
      dialogVisible: false,
      uploadDialogVisible: false,
      editForm: {
        unit_id: '',
        unit_number: '',
        actual_area: '',
        building_area: '',
        unit_type: '',
        status: '',
        rental_price: '',
        sale_price: '',
        property_fee_standard: '',
        orientation: '',
        facilities_desc: ''
      },
      rules: {
        unit_number: [
          { required: true, message: '请输入房间号', trigger: 'blur' }
        ],
        unit_type: [
          { required: true, message: '请选择房间类型', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.roomId = this.$route.params.id
    this.fetchRoomInfo()
    this.fetchEquipmentList()
    this.fetchContractInfo()
  },
  methods: {
    // 获取房间信息
    async fetchRoomInfo() {
      this.loading = true
      try {
        const response = await getRoomDetail(this.roomId)
        if (response.data.code === 200) {
          this.roomInfo = response.data.data
          this.roomImages = response.data.data.media_urls || []
        }
      } catch (error) {
        this.$message.error('获取房间详情失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 获取设备列表
    async fetchEquipmentList() {
      try {
        const response = await getRoomDevices(this.roomId)
        if (response.data.code === 200) {
          this.equipmentList = response.data.data
        }
      } catch (error) {
        this.$message.error('获取房间设备列表失败')
        console.error(error)
      }
    },
    // 获取合同信息
    async fetchContractInfo() {
      try {
        const response = await getRoomContract(this.roomId)
        if (response.data.code === 200 && response.data.data) {
          this.contractInfo = response.data.data
        } else {
          this.contractInfo = null
        }
      } catch (error) {
        // 合同不存在是正常情况，不在界面上提示错误
        console.error('获取合同信息失败', error)
        this.contractInfo = null
      }
    },
    // 返回上一页
    goBack() {
      if (this.roomInfo && this.roomInfo.floor && this.roomInfo.floor.floor_id) {
        this.$router.push(`/admin/assets/FloorDetail/${this.roomInfo.floor.floor_id}`)
      } else {
        // Fallback if data is not loaded yet
        this.$router.go(-1)
      }
    },
    // 打开编辑对话框
    openDialog() {
      this.editForm = JSON.parse(JSON.stringify(this.roomInfo))
      this.dialogVisible = true
    },
    // 提交表单
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 调用编辑接口
          console.log('编辑房间', this.editForm)
          this.$message.success('编辑成功')
          this.dialogVisible = false
          // 更新房间信息
          this.roomInfo = { ...this.roomInfo, ...this.editForm }
        } else {
          return false
        }
      })
    },
    // 上传房间图片
    uploadRoomImages() {
      this.uploadDialogVisible = true
    },
    // 提交上传
    submitUpload() {
      // 这里应该调用上传接口
      this.$message.success('图片上传成功')
      this.uploadDialogVisible = false
      // 模拟上传成功后更新图片列表
      this.fetchRoomImages()
    },
    // 查看合同详情
    viewContract() {
      this.$router.push(`/admin/contracts/detail/${this.contractInfo?.contract_number}`)
    },
    // 获取房间状态类型
    getRoomStatusType(status) {
      const statusMap = {
        '空置': 'info',
        '意向': 'warning',
        '已租': 'success',
        '已售': 'success',
        '装修中': 'warning',
        '维修中': 'danger',
        '待清洁': 'warning',
        '不可用': 'danger'
      }
      return statusMap[status] || 'info'
    },
    // 获取合同状态类型
    getContractStatusType(status) {
      const statusMap = {
        '生效中': 'success',
        '即将到期': 'warning',
        '已到期': 'danger',
        '已终止': 'info'
      }
      return statusMap[status] || 'info'
    },
    // 获取设备状态类型
    getEquipStatusType(status) {
      const statusMap = {
        '正常': 'success',
        '故障': 'danger',
        '维修中': 'warning',
        '报废': 'danger'
      }
      return statusMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.room-detail {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.breadcrumb {
  display: inline-block;
  margin-left: 20px;
}
.info-card, .contract-card, .room-image-card, .equipment-card {
  margin-bottom: 20px;
}
.card-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.info-item {
  margin-bottom: 15px;
}
.label {
  color: #606266;
  font-weight: bold;
}
.value {
  margin-left: 5px;
}
.room-image-container {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.room-images {
  width: 100%;
}
.room-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.room-image-placeholder {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}
.room-image-placeholder i {
  font-size: 48px;
  margin-bottom: 10px;
}
.upload-container {
  text-align: center;
}
</style> 